package com.ware.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.jfinal.core.JFinal;

public abstract class UploadUtil {	
	private static final String ACCESS_ID = "kYWkj03GXGUHsUMX";
    private static final String ACCESS_KEY = "mNqPXOQyrzzUyqBRIhjeDcPXxtq0AJ";
	
    private static OSSClient client = null;
    
	//图片文件BucketName域名.
	private static final String BucketName = "canyou-o2o";
	
	public static String getBucketName(){
		return BucketName;
	}
	
	public static OSSClient getOSSClient(){
		if (client == null) {
			client = new OSSClient("http://oss-cn-qingdao.aliyuncs.com", ACCESS_ID, ACCESS_KEY);
		}
		return client;
	}
	
	//获取阿里数据中心
	private static String getBucketLocation(OSSClient client) {
		//return client.getBucketLocation(getBucketName());
		return "oss-cn-qingdao.aliyuncs.com";
	}
	
	//判断是否sae环境.
	public static boolean isSae() {
		//return true;
		return true;
		//return !SaeUserInfo.getAppName().equals("appname");
	}
	//格式话路径信息
	public static String formatPath(String path){		
		if(path == null || path.trim().equals("")){
			return "";
		}
		return (path.endsWith("\\") || path.endsWith("/")) ? path : path+"/";		
	}
	
	//返回上传文件保存的临时路径.
	public static String getTempPath(int userId,String destPath){
		String tempPath = JFinal.me().getServletContext().getRealPath("/") + "/img/" + userId + "/"+formatPath(destPath);
		
		return tempPath;
	}
	
	//返回上传文件保存的临时路径.
	public static String getSavePath(int userId,String destPath,String base){
		String tempPath = JFinal.me().getServletContext().getRealPath("/") + "/img/" + userId + "/"+base+"/"+formatPath(destPath);
		return tempPath;
	}
	
	//根据用户id获取Storage文件存储路径.
	public static String getStoreFilePath(int userId){
		return String.valueOf(userId)+"/";			
	}
	
	//根据用户id获取Storage文件存储路径.
	public static String getStoreFilePath(int userId,String destPath){
		String storeDir = String.valueOf(userId);				
		String objPath = storeDir+"/";
		if(destPath != null && !destPath.trim().equals("")){
			String temp = destPath.trim();
			if(temp.startsWith("/")){
				temp = temp.substring(1);
			}
			if(!temp.equals("")){
				objPath += temp;
				if(!objPath.endsWith("/")){
					objPath += "/";
				}
			}			
		}
		return objPath;
	}
	
	//根据用户id获取Storage文件存储路径.
	public static String getStoreFilePath(int userId,String destPath,String base){
		String storeDir = String.valueOf(userId);				
		String objPath = storeDir+"/"+base+"/";
		if(destPath != null && !destPath.trim().equals("")){
			String temp = destPath.trim();
			if(temp.startsWith("/")){
				temp = temp.substring(1);
			}
			if(!temp.equals("")){
				objPath += temp;
				if(!objPath.endsWith("/")){
					objPath += "/";
				}
			}			
		}
		return objPath;
	}
	
	//判断是否是合法的图片文件.
	public static boolean checkImg(String fileName) {
		return Pattern.compile(".+?\\.(jpg|gif|bmp|png|jpeg)").matcher(fileName.toLowerCase()).matches();
	}
	
	//获取文件扩展名
	public static String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}
	
	//随机产生文件名
	public static String randFileName(String fileName) {
		Random random = new Random();
		return fileName = "" + random.nextInt(10000)	+ System.currentTimeMillis() + getFileExt(fileName);
	}
	
	//从全路径中获取文件名称.
	public static String parseFileName(String filePath){
		if (filePath.contains("\\")) {
			filePath = filePath.substring(filePath.lastIndexOf("\\") + 1);
		}else {
			filePath = filePath.substring(filePath.lastIndexOf("/") + 1);
		}
		return filePath;
	}	
	
	//缩放并保存图片到store中
	public static String resizeImageToStore(File srcFile,String fileKey,int width,int height) throws Exception{
		BufferedImage src = ImageIO.read(srcFile);
		BufferedImage obj = ImageUtil.resize(src, width, height, false);
		
		ByteArrayOutputStream bs = new ByteArrayOutputStream();          
		
		String path = "";
      
        try { 
        	ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);              
            ImageIO.write(obj, "JPEG",imOut); 
            
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(imOut.length());
            
            InputStream input = new ByteArrayInputStream(bs.toByteArray());             
            getOSSClient().putObject(getBucketName(), fileKey, input, objectMeta);      
            
            path = "http://" + getBucketName() + "." + getBucketLocation(client) + "/" + fileKey;            
        } catch (IOException e) { 
            e.printStackTrace(); 
            path = "";
        }  
       return path;
	}
	
	//将本地图片上传到storage中.
	public static String uploadImageToStore(String srcFile,String key) throws Exception{

		File file = new File(srcFile);

        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(file.length());
        // 可以在metadata中标记文件类型
        //objectMeta.setContentType("image/jpeg");

        InputStream input = new FileInputStream(file);
        getOSSClient().putObject(getBucketName(), key, input, objectMeta);        
        
        return "http://" + getBucketName() + "." + getBucketLocation(client) + "/" + key;
	}
	
	/**
	 * 返回图片文件全路径
	 * @param userId 用户id
	 * @param fileName 文件名.
	 * @return
	 */
	public static String getImageUrl(int userId,String fileName){		
		String filePath = String.valueOf(userId)+"/normal/"+fileName;
		return getImageUrl(filePath);
		
	}
	public static String getWxImageUrl(int userId,String fileName) {
		String filePath = String.valueOf(userId)+"/"+fileName;
		return getImageUrl(filePath);
	}
	/**
	 * 返回图片文件全路径.
	 * @param fileName
	 * @return
	 */
	public static String getImageUrl(String fileName){	
		if(UploadUtil.isSae()){
			//return new SaeStorage().getUrl( getImgDomain(),fileName);
			return "http://" + getBucketName() + "." + getBucketLocation(client) + "/" + fileName;
		}else{
			return "/img/"+fileName;
		}
	}
	
	public static void deleteExist(String path) {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}
	}
}